import 'dart:async';

import 'package:bruno/bruno.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pinput/pinput.dart';

import '../../network/UrlPath.dart';
import '../../r.dart';
import '../../utils/toast_utils.dart';
import '../../values/CommonParam.dart';
import '../../values/MyColors.dart';
import 'login_logic.dart';

class LoginPage extends StatefulWidget {
  final String title;

  const LoginPage({Key? key, required this.title}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final logic = Get.put(LoginLogic());
  final state = Get.find<LoginLogic>().state;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      /*可以通过设置 这个属性 防止键盘 覆盖内容 或者 键盘 撑起内容*/
      backgroundColor: Colors.white,
      body: Stack(
        children: [
          Image.asset(R.assetsImgBgLogin, fit: BoxFit.fitWidth),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              GestureDetector(
                child: Container(
                  margin: EdgeInsets.only(left: 29.r, top: 85.5.r),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text("您好，", style: TextStyle(color: MyColors.FFFEFEFE, fontSize: 26.r, fontWeight: FontWeight.bold)),
                      Text("欢迎进入面访调查系统。", style: TextStyle(color: MyColors.FFFEFEFE, fontSize: 19.r, fontWeight: FontWeight.bold)),
                    ],
                  ),
                ),
                onTap: () {
                  tapCount();
                },
              ),
              Expanded(
                child: Container(
                  margin: EdgeInsets.only(top: 36.5.r),
                  decoration: BoxDecoration(
                    gradient: const LinearGradient(
                      colors: [MyColors.FFD6E5F9, Colors.white],
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                    ),
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(15.r),
                      topRight: Radius.circular(15.r),
                    ),
                  ),
                  child: Column(
                    children: [
                      // 账号输入框
                      Container(
                        margin: EdgeInsets.fromLTRB(30.r, 32.r, 30.r, 0),
                        padding: EdgeInsets.only(left: 17.5.r, right: 20.5.r),
                        height: 45.r,
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.all(Radius.circular(10.r)),
                        ),
                        child: Row(
                          children: [
                            Container(
                              margin: EdgeInsets.only(right: 14.r),
                              child: Image.asset(R.assetsImgIconLogin2, width: 14.r),
                            ),
                            Flexible(
                              child: TextField(
                                controller: logic.userName,
                                autofocus: false,
                                style: TextStyle(color: MyColors.FF909399, fontSize: 15.r),
                                decoration: InputDecoration(
                                    //不需要输入框下划线
                                    border: InputBorder.none,
                                    hintText: '请输入手机号',
                                    hintStyle: TextStyle(color: MyColors.FF909399, fontSize: 15.r)),
                              ),
                            ),
                          ],
                        ),
                      ),
                      // 密码输入框
                      Container(
                        margin: EdgeInsets.fromLTRB(30.r, 15.r, 30.r, 0),
                        padding: EdgeInsets.only(left: 17.5.r, right: 20.5.r),
                        height: 45.r,
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.all(Radius.circular(10.r)),
                        ),
                        child: Row(
                          children: [
                            Container(
                              margin: EdgeInsets.only(right: 14.r),
                              child: Image.asset(R.assetsImgIconLogin4, width: 13.5.r),
                            ),
                            Obx(() {
                              return Flexible(
                                child: TextField(
                                  controller: logic.password,
                                  autofocus: false,
                                  obscureText: state.obscureText.value,
                                  style: TextStyle(color: MyColors.FF909399, fontSize: 15.r),
                                  decoration: InputDecoration(
                                      //不需要输入框下划线
                                      border: InputBorder.none,
                                      hintText: '请输入密码',
                                      hintStyle: TextStyle(color: MyColors.FF909399, fontSize: 15.r)),
                                ),
                              );
                            }),
                            GestureDetector(
                              child: Obx(() {
                                return SizedBox(
                                  height: 16.r,
                                  width: 16.r,
                                  child: Image.asset(state.obscureText.value ? R.assetsImgIconLogin3 : R.assetsImgIconLogin5, width: 16.r),
                                );
                              }),
                              onTap: () {
                                if (state.obscureText.value) {
                                  state.obscureText.value = false;
                                } else {
                                  state.obscureText.value = true;
                                }
                              },
                            ),
                          ],
                        ),
                      ),
                      Visibility(
                        visible: false,
                        child: Container(
                          margin: EdgeInsets.fromLTRB(30.r, 11.r, 30.r, 0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              TextButton(
                                style: TextButton.styleFrom(
                                  padding: const EdgeInsets.all(0),
                                ),
                                onPressed: () {
                                  // logic.goToPasswordResetPage();
                                },
                                child: Text("忘记密码", style: TextStyle(color: MyColors.FF1060DD, fontSize: 13.r)),
                              ),
                              TextButton(
                                style: TextButton.styleFrom(
                                  padding: const EdgeInsets.all(0),
                                ),
                                onPressed: () {
                                  // logic.goToPasswordResetPage();
                                },
                                child: Text("立即注册", style: TextStyle(color: MyColors.FF1060DD, fontSize: 13.r)),
                              ),
                            ],
                          ),
                        ),
                      ),
                      Expanded(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            Container(
                              margin: EdgeInsets.fromLTRB(30.r, 0.r, 30.r, 0),
                              child: Obx(() {
                                return BrnRadioButton(
                                  radioIndex: 0,
                                  isSelected: state.isSelected.value,
                                  childOnRight: true,
                                  mainAxisSize: MainAxisSize.max,
                                  child: RichText(
                                    text: TextSpan(children: [
                                      TextSpan(text: '我已阅读', style: TextStyle(color: MyColors.FF909399, fontSize: 13.r)),
                                      TextSpan(
                                          text: '《用户服务协议》',
                                          style: TextStyle(color: MyColors.FF1060DD, fontSize: 13.r),
                                          recognizer: TapGestureRecognizer()
                                            ..onTap = () {
                                              logic.goToWebViewPage();
                                            }),
                                      TextSpan(text: '和', style: TextStyle(color: MyColors.FF909399, fontSize: 13.r)),
                                      TextSpan(
                                          text: '《隐私政策》',
                                          style: TextStyle(color: MyColors.FF1060DD, fontSize: 13.r),
                                          recognizer: TapGestureRecognizer()
                                            ..onTap = () {
                                              logic.goToWebViewPage();
                                            }),
                                    ]),
                                  ),
                                  onValueChangedAtIndex: (index, value) {
                                    if (state.isSelected.value) {
                                      state.isSelected.value = false;
                                    } else {
                                      state.isSelected.value = true;
                                    }
                                  },
                                );
                              }),
                            ),
                            Container(
                              margin: EdgeInsets.only(top: 15.r, bottom: 80.r, left: 30.r, right: 30.r),
                              child: Column(
                                children: [
                                  ElevatedButton(
                                    style: ElevatedButton.styleFrom(
                                      padding: const EdgeInsets.all(0),
                                      backgroundColor: MyColors.FF0144B0,
                                      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(6))),
                                      minimumSize: Size(MediaQuery.of(context).size.width, 45.r)
                                    ),
                                    onPressed: () {
                                      logic.login();
                                    },
                                    child: Text("登录", style: TextStyle(color: Colors.white, fontSize: 17.r)),
                                  ),
                                  Visibility(
                                    visible: false,
                                    child: Container(
                                      margin: EdgeInsets.only(top: 20.r),
                                      child: TextButton(
                                        style: TextButton.styleFrom(
                                          padding: const EdgeInsets.all(0),
                                        ),
                                        onPressed: () {},
                                        child: Text("其他登录方式", style: TextStyle(color: MyColors.FF0144B0, fontSize: 16.r)),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // 底部弹窗切换
  void showRerouting() {
    print("123123");
    List<BrnCommonActionSheetItem> actions = [];
    actions.add(BrnCommonActionSheetItem(
      '选项一（开发）',
      actionStyle: BrnCommonActionSheetItemStyle.normal,
    ));
    actions.add(BrnCommonActionSheetItem(
      '选项一（测试）',
      actionStyle: BrnCommonActionSheetItemStyle.normal,
    ));
    actions.add(BrnCommonActionSheetItem(
      '选项一（生产）',
      actionStyle: BrnCommonActionSheetItemStyle.normal,
    ));
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (_) {
        return BrnCommonActionSheet(
          actions: actions,
          clickCallBack: (int index, BrnCommonActionSheetItem actionEle) {
            print(index);
            String title = actionEle.title;
            switch (index) {
              case 0:
                UrlPath.baseUrl = CommonParam.DEBUG_URL;
                break;
              case 1:
                UrlPath.baseUrl = CommonParam.TEST_URL;
                break;
              case 2:
                UrlPath.baseUrl = CommonParam.RELEASE_URL;
                break;
              default:
            }
          },
        );
      },
    );
  }

  // 输入框
  void showInput() {
    final defaultPinTheme = PinTheme(
      width: 42.r,
      height: 42.r,
      textStyle: TextStyle(fontSize: 20.r, color: MyColors.FF313336),
      decoration: BoxDecoration(
        color: MyColors.FFEDF1F5,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.transparent),
      ),
    );

    final focusedPinTheme = defaultPinTheme.copyWith(
      width: 45.r,
      height: 45.r,
      decoration: defaultPinTheme.decoration!.copyWith(
        border: Border.all(color: MyColors.FF1060DD),
      ),
    );

    showDialog(
        context: context,
        builder: (BuildContext context) {
          return Dialog(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(13.33.r),
              ),
              insetPadding: EdgeInsets.symmetric(horizontal: 24.0.r, vertical: 24.0.r),
              child: IntrinsicHeight(
                child: Container(
                  child: Column(
                    children: [
                      Container(
                        margin: EdgeInsets.only(top: 17.5.r),
                        child: Text(
                          "管理员模式",
                          style: TextStyle(color: Colors.black, fontSize: 16.r, fontWeight: FontWeight.bold),
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(
                          top: 11.5.r,
                          left: 16.r,
                          right: 16.r,
                        ),
                        height: 45.r,
                        child: Pinput(
                          length: 6,
                          defaultPinTheme: defaultPinTheme,
                          focusedPinTheme: focusedPinTheme,
                          autofocus: true,
                          onCompleted: (value) {
                            if (value == "111111") {
                              Navigator.of(context).pop('ok');
                              showRerouting();
                            } else {
                              toast.show("密码错误，耗子尾汁！！！");
                            }
                          },
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 11.5.r),
                        height: 45.r,
                        child: TextButton(
                          style: TextButton.styleFrom(
                            padding: const EdgeInsets.all(0),
                          ),
                          onPressed: () {
                            Navigator.of(context).pop('ok');
                          },
                          child: Text("确认", style: TextStyle(color: MyColors.FF2763B9, fontSize: 14.r, fontWeight: FontWeight.bold)),
                        ),
                      ),
                    ],
                  ),
                ),
              ));
        });
  }

  Timer? timer;
  int count = 0;

  /// 连续点击10次 切换baseUrl
  void tapCount() {
    count++;
    timer?.cancel();
    timer = Timer(Duration(milliseconds: 500), () {
      if (count >= 10) {
        showInput();
      }
      count = 0;
    });
  }

  @override
  void dispose() {
    Get.delete<LoginLogic>();
    super.dispose();
  }
}
